
/*上位机至下位机协议帧示例： C100230120L */
/* 下位机至上位机协议帧：L0002260000000001200120C */
                       

var SerialPort = require('serialport');
//Opening a Port
var serialPort = new SerialPort('COM7', {
    //波特率，可在设备管理器中对应端口的属性中查看
    baudRate : 115200,
    autoOpen:false
})
//连接串口后进行写入指令操作
serialPort.open(function (err) {
    console.log('IsOpen:',serialPort.isOpen)
    console.log('err:',err)
    if(!err){

        //serialPort.write("C111111111L\n")
        //serialPort.write("C222222222L\n")
        setTimeout(function() {
            serialPort.write("C222222222L\n")
            },1500);
    }
})
//指令监听
serialPort.on('data',function (data) {
    console.log('data received: '+data)
    data =String(data)                    //object转成字符串
    data = data.split("")                 //字符串转成char 数组
    if((data[0] == 'L')&&(data[23]=='C')){
        var gameState = data[1]
        var lightColor = data[2]
        var alcoholData = data.slice(3,7)
        alcoholData = alcoholData.map(Number) //转成数字数组
        var x_alcoholData = alcoholData.reduce(function(x,y){
            return x*10+y;
        });

        /*  剩下依此类推*/
        var userID = data.slice(7,11)
        var gameScore = data.slice(11,15)
        var gameTime = data.slice(15,19)
        var restTime = data.slice(19,23)

        console.log(alcoholData)
        console.log(x_alcoholData) 
    }   
})
//错误监听
serialPort.on('error',function (error) {
    console.log('error: '+error)
})

//获取端口列表
SerialPort.list(function (error, ports) {
    ports.forEach(function(port) {
        console.log(port.comName);
        console.log(port.pnpId);
        console.log(port.manufacturer);
    });
})

